﻿
#region Using

using GalaSoft.MvvmLight.Command;
using NetBay.Core.BusinessEntities.Connectors;
using Rio.Manager.Application.ViewModel.BaseClass;
using Rio.Framework.Localisation;
using System;
using System.Collections.ObjectModel;
using Rio.Applications.Web.Services;
using System.ServiceModel.DomainServices.Client;
using System.Windows;

using Rio.Manager.Application.ViewModel.Locator;
using Rio.Framework.Pages.Helpers;
using Rio.Framework.Pages.Context;
using NetBay.Core.BusinessEntities;
using Rio.Framework.Pages.AppCode.Enums;

using System.Linq;
using Rio.Framework.Pages;
using GalaSoft.MvvmLight.Messaging;

#endregion Using

namespace Rio.Manager.Application.ViewModel.Administration
{
    public class ConnectorTabViewModel : TabViewModelBase
    {
        #region Fields

        public RelayCommand InitializationCommand { get; set; }
        public RelayCommand ConnectorCommandCreate { get; set; }
        public RelayCommand ConnectorCommandModify { get; set; }
        public RelayCommand ConnectorCommandDelete { get; set; }
        public RelayCommand ConnectorCommandRefresh { get; set; }

        private string _ConnectorTitleList;
        private string _ConnectorCorrespondencesItemList;
        private string _ConnectorParametersItemList;
        private string _HeaderConnectorName;
        private string _HeaderConnectorDescription;
        private string _HeaderConnectorOrganization;
        private string _HeaderConnectorFolderTypeName;
        private string _HeaderCorrespondenceIndexName;
        private string _HeaderCorrespondenceIndexPosition;
        private string _HeaderCorrespondenceIndexDescription;
        private string _HeaderParametersERP;
        private string _HeaderParametersRIO;
        private string _HeaderParametersDescription;
        private string _RadTabItemHeaderConnectorCorrespondence;
        private string _RadTabItemHeaderConnectorParameters;
        private string _NewConnector;
        private string _DeleteConnector;
        private string _ModifyConnector;
        private string _RefreshConnector;
        private ObservableCollection<Connector> _ConnectorInformations;
        private ObservableCollection<Connector> _ConnectorInformationsSelected;
        private Boolean _CanAddConnector;
        private Boolean _CanUpdateConnector;
        private Boolean _CanDeleteConnector;
        private Boolean _CanRefreshConnector;

        #endregion Fields

        #region Properties

        public string ConnectorTitleList
        {
            get { return _ConnectorTitleList; }
            set
            {
                _ConnectorTitleList = value;
                RaisePropertyChanged("ConnectorTitleList");
            }
        }

        public string ConnectorCorrespondencesItemList
        {
            get { return _ConnectorCorrespondencesItemList; }
            set
            {
                _ConnectorCorrespondencesItemList = value;
                RaisePropertyChanged("ConnectorCorrespondencesItemList");
            }
        }

        public string ConnectorParametersItemList
        {
            get { return _ConnectorParametersItemList; }
            set
            {
                _ConnectorParametersItemList = value;
                RaisePropertyChanged("ConnectorParametersItemList");
            }
        }

        public string HeaderConnectorName
        {
            get { return _HeaderConnectorName; }
            set
            {
                _HeaderConnectorName = value;
                RaisePropertyChanged("HeaderConnectorName");
            }
        }

        public string HeaderConnectorDescription
        {
            get { return _HeaderConnectorDescription; }
            set
            {
                _HeaderConnectorDescription = value;
                RaisePropertyChanged("HeaderConnectorDescription");
            }
        }

        public string HeaderConnectorOrganization
        {
            get { return _HeaderConnectorOrganization; }
            set
            {
                _HeaderConnectorOrganization = value;
                RaisePropertyChanged("HeaderConnectorOrganization");
            }
        }

        public string HeaderConnectorFolderTypeName
        {
            get { return _HeaderConnectorFolderTypeName; }
            set
            {
                _HeaderConnectorFolderTypeName = value;
                RaisePropertyChanged("HeaderConnectorFolderTypeName");
            }
        }

        public string RadTabItemHeaderConnectorCorrespondence
        {
            get { return _RadTabItemHeaderConnectorCorrespondence; }
            set
            {
                _RadTabItemHeaderConnectorCorrespondence = value;
                RaisePropertyChanged("RadTabItemHeaderConnectorCorrespondence");
            }
        }

        public string RadTabItemHeaderConnectorParameters
        {
            get { return _RadTabItemHeaderConnectorParameters; }
            set
            {
                _RadTabItemHeaderConnectorParameters = value;
                RaisePropertyChanged("RadTabItemHeaderConnectorParameters");
            }
        }

        public string HeaderCorrespondenceIndexName
        {
            get { return _HeaderCorrespondenceIndexName; }
            set
            {
                _HeaderCorrespondenceIndexName = value;
                RaisePropertyChanged("HeaderCorrespondenceIndexName");
            }
        }

        public string HeaderCorrespondenceIndexPosition
        {
            get { return _HeaderCorrespondenceIndexPosition; }
            set
            {
                _HeaderCorrespondenceIndexPosition = value;
                RaisePropertyChanged("HeaderCorrespondenceIndexPosition");
            }
        }

        public string HeaderCorrespondenceIndexDescription
        {
            get { return _HeaderCorrespondenceIndexDescription; }
            set
            {
                _HeaderCorrespondenceIndexDescription = value;
                RaisePropertyChanged("HeaderCorrespondenceIndexDescription");
            }
        }

        public string HeaderParametersERP
        {
            get { return _HeaderParametersERP; }
            set
            {
                _HeaderParametersERP = value;
                RaisePropertyChanged("HeaderParametersERP");
            }
        }

        public string HeaderParametersRIO
        {
            get { return _HeaderParametersRIO; }
            set
            {
                _HeaderParametersRIO = value;
                RaisePropertyChanged("HeaderParametersRIO");
            }
        }

        public string HeaderParametersDescription
        {
            get { return _HeaderParametersDescription; }
            set
            {
                _HeaderParametersDescription = value;
                RaisePropertyChanged("HeaderParametersDescription");
            }
        }

        public string NewConnector
        {
            get { return _NewConnector; }
            set
            {
                _NewConnector = value;
                 RaisePropertyChanged("NewConnector");
            }
        }
        public string DeleteConnector
        {
            get { return _DeleteConnector; }
            set
            {
                _DeleteConnector = value;
                RaisePropertyChanged("DeleteConnector");
            }
        }
        public string ModifyConnector
        {
            get { return _ModifyConnector; }
            set
            {
                _ModifyConnector = value;
                RaisePropertyChanged("ModifyConnector");
            }
        }
        public string RefreshConnector
        {
            get { return _RefreshConnector; }
            set
            {
                _RefreshConnector = value;
                RaisePropertyChanged("RefreshConnector");
            }
        }

        public ObservableCollection<Connector> ConnectorInformationList
        {
            get { return _ConnectorInformations; }
            set
            {
                _ConnectorInformations = value;
                RaisePropertyChanged("ConnectorInformationList");               
            }
        }

        public ObservableCollection<Connector> ConnectorInformationsSelected
        {
            get { return _ConnectorInformationsSelected; }
            set
            {
                _ConnectorInformationsSelected = value;
                RaisePropertyChanged("ConnectorInformationsSelected");
            }
        }

        public Boolean CanAddConnector
        {
            get { return _CanAddConnector; }
            set
            {
                _CanAddConnector = value;
                RaisePropertyChanged("CanAddConnector");
            }
        }

        public Boolean CanUpdateConnector
        {
            get { return _CanUpdateConnector; }
            set
            {
                _CanUpdateConnector = value;
                RaisePropertyChanged("CanUpdateConnector");
            }
        }

        public Boolean CanDeleteConnector
        {
            get { return _CanDeleteConnector; }
            set
            {
                _CanDeleteConnector = value;
                RaisePropertyChanged("CanDeleteConnector");
            }
        }

        public Boolean CanRefreshConnector
        {
            get { return _CanRefreshConnector; }
            set
            {
                _CanRefreshConnector = value;
                RaisePropertyChanged("CanRefreshConnector");
            }
        }

        #endregion Properties

        #region Constructor and Initialization

        public ConnectorTabViewModel()
            : base()
        {
            CanCloseTab = true;
            TabIcon = new Uri("/Rio.Manager.Application;component/Assets/Images/Connector_Onglet_Manage.png", UriKind.Relative);
        }

        public override void InitCommands()
        {
            InitializationCommand = new RelayCommand(Initialization);
            ConnectorCommandCreate = new RelayCommand(ConnectorCmdCreate);
            ConnectorCommandModify = new RelayCommand(ConnectorCmdModify);
            ConnectorCommandDelete = new RelayCommand(ConnectorCmdDelete);
            ConnectorCommandRefresh = new RelayCommand(ConnectorCmdRefresh); 
        }

        private void Initialization()
        {
            InitLabels();
            InitConnectorTable();
            InitsProperties();

            //Message to refresh connector consultation register.
            Messenger.Default.Register<NotificationMessage>(this, InitConnectorTable);
        }

        public void InitsProperties()
        {
            CanUpdateConnector = false;
            CanDeleteConnector = false;
        }

        public override void InitLabels()
        {
            //Labels initialization.
            TabTitle = Resx.GetLabel(ResxRioManager.CONNECTOR_MANAGE);
            ConnectorTitleList = Resx.GetLabel(ResxRioManager.CONNECTOR_TITLE_LIST);
            ConnectorCorrespondencesItemList = Resx.GetLabel(ResxRioManager.CONNECTOR_CORRESPONDENCES_ITEM_LIST);
            ConnectorParametersItemList = Resx.GetLabel(ResxRioManager.CONNECTOR_PARAMETERS_ITEM_LIST);
            NewConnector = Resx.GetLabel(ResxCommon.NEW);
            ModifyConnector = Resx.GetLabel(ResxCommon.MODIFY);
            DeleteConnector = Resx.GetLabel(ResxCommon.DELETE);
            RefreshConnector = Resx.GetLabel(ResxCommon.REFRESH);
            HeaderConnectorName = Resx.GetLabel(ResxRioManager.CONNECTOR_NAME);
            HeaderConnectorDescription = Resx.GetLabel(ResxRioManager.CONNECTOR_DESCRIPTION);
            HeaderConnectorOrganization = Resx.GetLabel(ResxRioManager.CONNECTOR_ORGANIZATION);
            HeaderConnectorFolderTypeName = Resx.GetLabel(ResxRioManager.CONNECTOR_FOLDER_TYPE_NAME);
            RadTabItemHeaderConnectorCorrespondence = Resx.GetLabel(ResxRioManager.CONNECTOR_CORRESPONDENCE);
            RadTabItemHeaderConnectorParameters = Resx.GetLabel(ResxRioManager.CONNECTOR_PARAMETERS);
            HeaderCorrespondenceIndexName = Resx.GetLabel(ResxRioManager.CONNECTOR_CORRESPONDENCE_INDEX_NAME);
            HeaderCorrespondenceIndexPosition = Resx.GetLabel(ResxRioManager.CONNECTOR_CORRESPONDENCE_INDEX_POSITION);
            HeaderCorrespondenceIndexDescription = Resx.GetLabel(ResxRioManager.CONNECTOR_CORRESPONDENCE_INDEX_DESCRIPTION);
            HeaderParametersERP = Resx.GetLabel(ResxRioManager.CONNECTOR_PARAMETERS_CUSTOMER);
            HeaderParametersRIO = Resx.GetLabel(ResxRioManager.CONNECTOR_PARAMETERS_RIO);
            HeaderParametersDescription = Resx.GetLabel(ResxRioManager.CONNECTOR_PARAMETERS_DESCRIPTION);
        }

        public void InitConnectorTable(NotificationMessage p_oMsg = null)
        {
            BusyIndicator.Clear();
            BusyIndicator.AddBusyTask();

            //Connector Table Initialization.
            BusinessEntitiesDomainContext l_oBEDomainContext = new BusinessEntitiesDomainContext();
            var query = l_oBEDomainContext.GetConnectorInformationListQuery();
            l_oBEDomainContext.Load(query, GetConnectorList, null);

            //Initialize the ConnectorInformationsSelected property.
            ConnectorInformationsSelected = new ObservableCollection<Connector>();           
        }

        #endregion Constructor and Initialization

        #region Methods

        /// <summary>Gets the connector list.</summary>
        /// <param name="e">Connector List</param>
        private void GetConnectorList(LoadOperation<Connector> e)
        {
            BusyIndicator.RemoveBusyTask();

            if (!e.HasError)
            {
                //Built the connector list.
                ConnectorInformationList = new ObservableCollection<Connector>(e.Entities);

                //Inits the properties.
                InitsProperties();
            }
        }

        /// <summary>Gets connectors information to update.</summary>        
        private void RetrievesConnectorInformationToUpdate()
        {
            //Retrieves connector Information.
            ConnectorAddTabViewModel newConnectorToUpdate = ViewModelLocator.ConnectorAddTabStatic;

            Action<TabViewModelBase> action = (tab =>
            {
                newConnectorToUpdate.ConnectorInformationToUpdate = ConnectorInformationsSelected;

                //Modify Mode.
                newConnectorToUpdate.IsModifyMode = true;

                //Retrieves Organization connector.
                Organizations = new ObservableCollection<Organization>();
                OrganizationComparer L_oOrganizationComparer = new OrganizationComparer();
                foreach (Group g in GlobalWebContext.CurrentUser.GroupList)
                {
                    foreach (Organization org in g.OrganizationList)
                    {
                        if (!Organizations.Contains(org, L_oOrganizationComparer))
                        {
                            if (GlobalWebContext.OrganizationHaveFolderTypeRight(org, AppDisplayMode.Admin))
                            {
                                Organizations.Add(org);
                            }
                        }
                    }
                }
                foreach (Organization l_oOragnisationConnecteurtoUpdate in Organizations)
                {
                    if (l_oOragnisationConnecteurtoUpdate.Identifier == ConnectorInformationsSelected[0].OrganizationCode)
                    {
                        //SelectedOrganization = l_oOragnisationConnecteurtoUpdate;
                        newConnectorToUpdate.SelectedOrganization = l_oOragnisationConnecteurtoUpdate;
                        break;
                    }
                }

                //Retrieves FolderType.
                FolderTypes = new ObservableCollection<FolderType>();
                FolderTypeComparer L_oFolderTypeComparer = new FolderTypeComparer();
                foreach (FolderType FolderTypeInOrga in newConnectorToUpdate.SelectedOrganization.FolderTypesList)
                {
                    foreach (Group UserGroup in GlobalWebContext.CurrentUser.GroupList)
                    {
                        if ((UserGroup.FolderTypeRigthList.Contains(FolderTypeInOrga, L_oFolderTypeComparer)) && ((UserGroup.IsAdministrator)))
                        {
                            FolderTypes.Add(FolderTypeInOrga);
                        }
                    }
                }
                foreach (FolderType l_oFolderTypeConnecteurtoUpdate in FolderTypes)
                {
                    if (l_oFolderTypeConnecteurtoUpdate.Identifier == ConnectorInformationsSelected[0].FolderTypeId)
                    {
                        //SelectedOrganization = l_oOragnisationConnecteurtoUpdate;
                        newConnectorToUpdate.SelectedFolderType = l_oFolderTypeConnecteurtoUpdate;
                        break;
                    }
                }

                //Retrieves Name and description connector.
                newConnectorToUpdate.ConnectorNameAdd = ConnectorInformationsSelected[0].ConnectorName;
                newConnectorToUpdate.ConnectorDescriptionAdd = ConnectorInformationsSelected[0].ConnectorDescription;

                //Retrieves parameters.
                newConnectorToUpdate.ConnectorParameterList = new System.Collections.ObjectModel.ObservableCollection<ConnectorParameters>(ConnectorInformationsSelected[0].LstConnectorParameters.Cast<ConnectorParameters>());

                //Retrieves correspondence.
                newConnectorToUpdate.ConnectorCorrespondenceList = new System.Collections.ObjectModel.ObservableCollection<ConnectorCorrespondence>(ConnectorInformationsSelected[0].LstConnectorCorrespondence.Cast<ConnectorCorrespondence>());
                newConnectorToUpdate.ConnectorCorrespondenceListSelected = new System.Collections.ObjectModel.ObservableCollection<ConnectorCorrespondence>(ConnectorInformationsSelected[0].LstConnectorCorrespondence.Cast<ConnectorCorrespondence>());
            });
           
            //Open the connector added page for updated connector.
            AddTab(newConnectorToUpdate, action);
        }
        
        #endregion Methods

        #region Commands

        /// <summary>Create a new connector.</summary>
        public void ConnectorCmdCreate()
        {
            //Open the connector added page.
            ConnectorAddTabViewModel newConnectorToAdd = ViewModelLocator.ConnectorAddTabStatic;
            newConnectorToAdd.ConnectorInformationToUpdate = null;
            newConnectorToAdd.SelectedOrganization = null;
            newConnectorToAdd.SelectedFolderType = null;
            newConnectorToAdd.IsModifyMode = false;
            AddTab(newConnectorToAdd);
        }

        /// <summary>Modify a connector.</summary>
        public void ConnectorCmdModify()
        {
            //Variable declaration.            
            Boolean l_oCanDeleteConnectorTemp = CanDeleteConnector;
            Boolean l_oCanUpdateConnectorTemp = CanUpdateConnector;
            MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow();

            //Test only one connector must be selected.
            switch (ConnectorInformationsSelected.Count)
            {
                case 0:
                    //Message user before modify.
                    L_oMessage = new MessageBoxChildWindow(String.Empty, Resx.GetLabel(ResxRioManager.CONNECTOR_UPDATE_NOTSELECTED), MessageBoxButtons.Ok, MessageBoxIcon.Warning);
                    L_oMessage.Show();
                    L_oMessage.Closed += (s, ev) =>
                    {
                        //Properties values.
                        CanDeleteConnector = l_oCanDeleteConnectorTemp;
                        CanUpdateConnector = l_oCanUpdateConnectorTemp;
                    };                   
                    break;
                case 1:
                    //Retrieves informations for update.
                    RetrievesConnectorInformationToUpdate();

                    break;
                default:
                    //Only one connector must be selected.
                    L_oMessage = new MessageBoxChildWindow(String.Empty, Resx.GetLabel(ResxRioManager.CONNECTOR_UPDATE_MOREONE), MessageBoxButtons.Ok, MessageBoxIcon.Warning);
                    L_oMessage.Show();
                    L_oMessage.Closed += (s, ev) =>
                    {
                        //Properties values.
                        CanDeleteConnector = l_oCanDeleteConnectorTemp;
                        CanUpdateConnector = l_oCanUpdateConnectorTemp;
                    };                   
                    break;
            }
        }

        /// <summary>Delete connectors.</summary>
        public void ConnectorCmdDelete()
        {
            //Variable declaration.
            string l_sConnectorIdList =string.Empty;
            Boolean l_oCanDeleteConnectorTemp = CanDeleteConnector;
            Boolean l_oCanUpdateConnectorTemp = CanUpdateConnector;
            MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow();

            //Test for delected the connector.
            if (ConnectorInformationsSelected.Count == 0 || ConnectorInformationsSelected == null)
            {
                L_oMessage = new MessageBoxChildWindow(String.Empty, Resx.GetLabel(ResxRioManager.CONNECTOR_DELETE_MSG), MessageBoxButtons.Ok, MessageBoxIcon.Warning);
                L_oMessage.Show();
                L_oMessage.Closed += (s, ev) =>
                {
                    //Properties values.
                    CanDeleteConnector = l_oCanDeleteConnectorTemp;
                    CanUpdateConnector = l_oCanUpdateConnectorTemp;
                };
                return;
            }

            //Connector Id List selected.
            foreach (Connector l_oConnectorListId in ConnectorInformationsSelected)
            {
                l_sConnectorIdList = l_sConnectorIdList + l_oConnectorListId.ConnectorId + ";";
            }
            l_sConnectorIdList = l_sConnectorIdList.Substring(0, l_sConnectorIdList.Length - 1);

            //Message user before deleting.
            L_oMessage = new MessageBoxChildWindow(String.Empty, Resx.GetLabel(ResxRioManager.CONNECTOR_DELETE_MSG_CONFIRM), MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            L_oMessage.Show();
            L_oMessage.Closed += (s, ev) =>
            {
                if (L_oMessage.Result == MessageBoxResult.Yes)
                {
                    //Delete.
                    BusinessEntitiesDomainContext l_oBEDomainContext = new BusinessEntitiesDomainContext();
                    l_oBEDomainContext.DeleteConnectorByListConnectorId(l_sConnectorIdList, result =>
                                {
                                    if (result.HasError)
                                    {
                                        //Error.
                                        L_oMessage = new MessageBoxChildWindow(String.Empty, Resx.GetLabel(ResxRioManager.CONNECTOR_DELETE_ERROR) + Environment.NewLine + result.Error.Message, MessageBoxButtons.Ok, MessageBoxIcon.Error);
                                        L_oMessage.Show();
                                    }
                                    else
                                    {

                                        //Succes.
                                        L_oMessage = new MessageBoxChildWindow(String.Empty, Resx.GetLabel(ResxRioManager.CONNECTOR_DELETE_SUCCES), MessageBoxButtons.Ok, MessageBoxIcon.Information);
                                        L_oMessage.Show();

                                        //Refresh table.
                                        InitConnectorTable();
                                    }
                                },
                                null);
                }
                else
                {
                    //Properties values.
                    CanDeleteConnector = l_oCanDeleteConnectorTemp;
                    CanUpdateConnector = l_oCanUpdateConnectorTemp;
                }
            };
        }

        /// <summary>Refresh a connector.</summary>
        public void ConnectorCmdRefresh()
        {
            //Refresh table.
            InitConnectorTable();
        }

        #endregion Commands
    }
}
